import os
import time
import subprocess
import re
import cv2
from PIL import Image
import dxomark.analyzer.lightingcontrol as lc

def get_image_aspect_ratio(image_path):
    try:
        # 打开图片
        img = Image.open(image_path)
        # 获取图片尺寸
        width, height = img.size
        print(width,height)
        # 计算长宽比例
        aspect_ratio = width / height
        return aspect_ratio
    except IOError:
        print("无法打开图片:", image_path)
        return None


def camera_capture(serial, num):
    # os.system("adb connect {}".format(serial))
    # time.sleep(1)
    # os.system("adb devices")
    # print()
    os.system("adb  -s {} shell input keyevent 224".format(serial))
    time.sleep(1)

    # 解锁屏幕（前提需要在设置里面把手机登录的密码这些都关掉）
    os.system("adb -s {} shell  input keyevent 82".format(serial))
    time.sleep(1)
    # os.system("adb -s {} shell  rm -rf /sdcard/DCIM/Camera/*.jpg".format(serial))
    # time.sleep(3)  # 清除旧的照片
    # 启动相机
    os.system("adb -s {} shell am start -a android.media.action.STILL_IMAGE_CAMERA ".format(serial))
    time.sleep(3)
    # 循环点击拍照按钮100次
    for i in range(1, int(num) + 1):
        lc.ensureLightingControlIsRunning()
        lc.runSequence('Trigger')
        # tm.triggerImmediately()
        # stopSequence()
        time.sleep(3)  # 拍完一张后，间隔3s，再拍下一张
    time.sleep(3)
    result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format(serial))
    # print('原始', result2)
    result2 = result2.decode("utf-8")
    result2 = result2.strip().splitlines()[1:]
    # print('result2', result2)
    OPG = []
    # result = []
    try:
        for i in result2:
            obj = re.compile(r'(.*?).jpg')
            result = obj.findall(i.split(' ')[-1])
            if result:
                OPG.append(result)
        # print(result)
    except Exception as e:
        print(e)
    # print('循环外', result)
    lister = list(sorted(OPG)[-1])
    # lister.insert(8, '_')
    Strer = ''.join(lister)
    name = Strer + '.jpg'
    file_dir = "F:/red/" + name
    # os.path.abspath(os.path.join(os.getcwd(), "..")) +
    print('最新的第{}张图片'.format(1), name)
    os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(serial, name, file_dir))
    os.system("adb  -s {} shell input keyevent 26".format(serial))
    return file_dir
    # print("phone_id_adb:", name2)
    # create_dir(name1, name2, name3)
    # print("phone_id_adb2:", name1, name2, name3)
    # # 导出刚刚拍的100张照片, 再由测试人员手动Check相片质量
    # print('zrs1700')
    # time.sleep(3)
    # os.system(
    #     'cd /d d:/result_photo/{}/{}/{}/ & adb -s {} pull /sdcard/DCIM/Camera/'.format(name1, str(name2), name3,
    #                                                                                    serial))
    # os.system("adb  -s {} shell input keyevent 26".format(serial))


def camera_capture_zoom(serial, num):
    # os.system("adb connect {}".format(serial))
    # time.sleep(1)
    # os.system("adb devices")
    # print()
    os.system("adb  -s {} shell input keyevent 224".format(serial))
    time.sleep(1)

    # 解锁屏幕（前提需要在设置里面把手机登录的密码这些都关掉）
    os.system("adb -s {} shell  input keyevent 82".format(serial))
    time.sleep(1)
    # os.system("adb -s {} shell  rm -rf /sdcard/DCIM/Camera/*.jpg".format(serial))
    # time.sleep(3)  # 清除旧的照片
    # 启动相机
    os.system("adb -s {} shell am start -a android.media.action.STILL_IMAGE_CAMERA ".format(serial))
    time.sleep(3)
    os.system("adb -s {} shell  input keyevent 24".format(serial))
    time.sleep(1)
    # 循环点击拍照按钮100次
    for i in range(1, int(num) + 1):
        lc.ensureLightingControlIsRunning()
        lc.runSequence('Trigger')
        # tm.triggerImmediately()
        # stopSequence()
        time.sleep(3)  # 拍完一张后，间隔3s，再拍下一张
    os.system("adb -s {} shell  input keyevent 25".format(serial))
    time.sleep(3)
    result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format(serial))
    # print('原始', result2)
    result2 = result2.decode("utf-8")
    result2 = result2.strip().splitlines()[1:]
    # print('result2', result2)
    OPG = []
    # result = []
    try:
        for i in result2:
            obj = re.compile(r'(.*?).jpg')
            result = obj.findall(i.split(' ')[-1])
            if result:
                OPG.append(result)
        # print(result)
    except Exception as e:
        print(e)
    # print('循环外', result)
    lister = list(sorted(OPG)[-1])
    # lister.insert(8, '_')
    Strer = ''.join(lister)
    name = Strer + '.jpg'
    file_dir = "F:/red/" + name
    # os.path.abspath(os.path.join(os.getcwd(), "..")) +
    print('最新的第{}张图片'.format(1), name)
    os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(serial, name, file_dir))
    os.system("adb  -s {} shell input keyevent 26".format(serial))
    return file_dir
    # print("phone_id_adb:", name2)
    # create_dir(name1, name2, name3)
    # print("phone_id_adb2:", name1, name2, name3)
    # # 导出刚刚拍的100张照片, 再由测试人员手动Check相片质量
    # print('zrs1700')
    # time.sleep(3)
    # os.system(
    #     'cd /d d:/result_photo/{}/{}/{}/ & adb -s {} pull /sdcard/DCIM/Camera/'.format(name1, str(name2), name3,
    #                                                                                    serial))
    # os.system("adb  -s {} shell input keyevent 26".format(serial))
def video_capture(serial, num):
    # os.system("adb connect {}".format(serial))
    # time.sleep(1)
    # os.system("adb devices")
    print()
    os.system("adb  -s {} shell input keyevent 224".format(serial))
    time.sleep(1)

    # 解锁屏幕（前提需要在设置里面把手机登录的密码这些都关掉）
    os.system("adb -s {} shell  input keyevent 82".format(serial))
    time.sleep(1)
    # os.system("adb -s {} shell  rm -rf /sdcard/DCIM/Camera/*.jpg".format(serial))
    # time.sleep(3)  # 清除旧的照片
    # 启动相机
    os.system("adb -s {} shell am start -a android.media.action.VIDEO_CAPTURE".format(serial))
    time.sleep(2)
    # os.system("adb -s {} shell input swipe 300 1700 600 1700".format(serial))
    # ensureLightingControlIsRunning(simulated=True)  # 模拟
    # ensureTimerPilotIsRunning()
    # tm.connectDigitalTrigger()
    lc.ensureLightingControlIsRunning()
    lc.runSequence('Trigger')
    time.sleep(float(num))
    lc.ensureLightingControlIsRunning()
    lc.runSequence('Trigger')
    time.sleep(1)
    os.system("adb  -s {} shell input keyevent 3".format(serial))
    time.sleep(3)
    result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format(serial))
    # print('原始', result2)
    result2 = result2.decode("utf-8")
    result2 = result2.strip().splitlines()[1:]
    # print('result2', result2)
    OPG = []
    time.sleep(3)
    # result = []
    try:
        for i in result2:

            obj = re.compile(r'(.*?).mp4')
            result = obj.findall(i.split(' ')[-1])
            if result:
                OPG.append(result)
        # print(result)
    except Exception as e:
        print(e)
    print(OPG)
    # print('循环外', result)
    lister = list(sorted(OPG)[-1])
    # lister.insert(8, '_')
    Strer = ''.join(lister)
    name = Strer + '.mp4'
    file_dir = "F:/red/" + name
    # os.path.abspath(os.path.join(os.getcwd(), "..")) +
    print('最新的第{}张图片'.format(1), name)
    os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(serial, name, file_dir))
    print(file_dir)
    os.system("adb  -s {} shell input keyevent 26".format(serial))
    return file_dir

def video_capture_zoom(serial, num):
    # os.system("adb connect {}".format(serial))
    # time.sleep(1)
    # os.system("adb devices")
    print()
    os.system("adb  -s {} shell input keyevent 224".format(serial))
    time.sleep(1)

    # 解锁屏幕（前提需要在设置里面把手机登录的密码这些都关掉）
    os.system("adb -s {} shell  input keyevent 82".format(serial))
    time.sleep(1)
    # os.system("adb -s {} shell  rm -rf /sdcard/DCIM/Camera/*.jpg".format(serial))
    # time.sleep(3)  # 清除旧的照片
    # 启动相机
    os.system("adb -s {} shell am start -a android.media.action.VIDEO_CAPTURE".format(serial))
    time.sleep(2)
    os.system("adb -s {} shell  input keyevent 24".format(serial))
    time.sleep(1)
    # os.system("adb -s {} shell input swipe 300 1700 600 1700".format(serial))
    # ensureLightingControlIsRunning(simulated=True)  # 模拟
    # ensureTimerPilotIsRunning()
    # tm.connectDigitalTrigger()
    lc.ensureLightingControlIsRunning()
    lc.runSequence('Trigger')
    time.sleep(float(num))
    lc.ensureLightingControlIsRunning()
    lc.runSequence('Trigger')
    time.sleep(1)
    os.system("adb -s {} shell  input keyevent 25".format(serial))
    time.sleep(1)
    os.system("adb  -s {} shell input keyevent 3".format(serial))
    time.sleep(3)
    result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format(serial))
    # print('原始', result2)
    result2 = result2.decode("utf-8")
    result2 = result2.strip().splitlines()[1:]
    # print('result2', result2)
    OPG = []
    time.sleep(3)
    # result = []
    try:
        for i in result2:

            obj = re.compile(r'(.*?).mp4')
            result = obj.findall(i.split(' ')[-1])
            if result:
                OPG.append(result)
        # print(result)
    except Exception as e:
        print(e)
    print(OPG)
    # print('循环外', result)
    lister = list(sorted(OPG)[-1])
    # lister.insert(8, '_')
    Strer = ''.join(lister)
    name = Strer + '.mp4'
    file_dir = "F:/red/" + name
    # os.path.abspath(os.path.join(os.getcwd(), "..")) +
    print('最新的第{}张图片'.format(1), name)
    os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(serial, name, file_dir))
    print(file_dir)
    os.system("adb  -s {} shell input keyevent 26".format(serial))
    return file_dir


def video_switch_photo(file_dir_video):
    vidcap = cv2.VideoCapture(file_dir_video)
    success, image = vidcap.read()
    count = -1
    while success:
        count += 1
        cv2.imwrite("frame%d.jpg" % count, image)
        success, image = vidcap.read()

    return "frame%d.jpg" % count


def deal_cmd(cmd):
    pi = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)

    # print(pi.stdin.read())
    return pi.stdout.read()

# video_capture('R58M74FN27R',3)
# ratio = get_image_aspect_ratio(r'F:\red\PXL_20240522_180003629.jpg')
# print(ratio)
# print(4/3)
# print(video_switch_photo(r'F:\red\PXL_20240522_235153516.mp4'))
# video_capture('28311FDH3000SF',2)
# # # camera_capture('27021FDH3001L0',1)
# # # camera_capture('R58M74FN27R',1)
# # # camera_capture('ca62fb87',1)
# # # camera_capture('3A091FDJG007P7',1)
# # # camera_capture('28311FDH3000SF',1)
# sre = '1B231FDEE001CS'
# camera_capture_zoom(sre,1)
video_capture('R58M74FN27R',9)
# time.sleep(3)
# result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format(sre))
# # print('原始', result2)
# result2 = result2.decode("utf-8")
# result2 = result2.strip().splitlines()[1:]
# # print('result2', result2)
# OPG = []
# # result = []
# try:
#     for i in result2:
#         print(i)
#         obj = re.compile(r'(.*?).jpg')
#         result = obj.findall(i.split(' ')[-1])
#         # obj = re.compile(r'IMG(.*?).jpg')
#         # result = obj.findall(i)
#         # if result == []:
#         #     obj = re.compile(r'PXL(.*?).jpg')
#         #     result = obj.findall(i)
#         # if result == []:
#         #     obj = re.compile(r'(.*?).jpg')
#         #     result = obj.findall(i.split(' ')[-1])
#         if result:
#             OPG.append(result)
#     # print(result)
# except Exception as e:
#     print(e)
# # print('循环外', result)
# lister = list(sorted(OPG)[-1])
# # lister.insert(8, '_')
# Strer = ''.join(lister)
# # name = 'PXL' + Strer + '.jpg'
# # name1 = 'IMG' + Strer + '.jpg'
# name = Strer + '.jpg'
# file_dir = "F:/red/" + name
# # os.path.abspath(os.path.join(os.getcwd(), "..")) +
# print('最新的第{}张图片'.format(1), name)
# # os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(sre, name1, file_dir))
# # time.sleep(1)
# os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(sre, name, file_dir))
# # time.sleep(1)
# # os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format(sre, name2, file_dir))

# video_capture('R4SW4LUW6HW8VCEI',10)
# time.sleep(3)
# result2 = deal_cmd('adb -s {} shell ls -l /sdcard/DCIM/Camera'.format('R4SW4LUW6HW8VCEI'))
# # print('原始', result2)
# result2 = result2.decode("utf-8")
# result2 = result2.strip().splitlines()[1:]
# # print('result2', result2)
# OPG = []
# # result = []
# try:
#     for i in result2:
#
#         obj = re.compile(r'(.*?).mp4')
#         result = obj.findall(i.split(' ')[-1])
#         if result:
#             OPG.append(result)
#     # print(result)
# except Exception as e:
#     print(e)
# # print('循环外', result)
# lister = list(sorted(OPG)[-1])
# # lister.insert(8, '_')
# Strer = ''.join(lister)
# name = Strer + '.mp4'
# file_dir = "F:/red/" + name
# # os.path.abspath(os.path.join(os.getcwd(), "..")) +
# print('最新的第{}张图片'.format(1), name)
# os.system(' adb  -s {} pull /sdcard/DCIM/Camera/{}  {}'.format('R4SW4LUW6HW8VCEI', name, file_dir))
# print(file_dir)
